<?php
/**首页
 * Created by PhpStorm.
 * User: C。
 * Date: 2019/8/12
 * Time: 15:10
 */
namespace app\admin\controller;

use app\common\model\News as NewsModel;
use app\common\model\LogAdmin as LogAdminModel;
use app\common\model\Company as CompanyModel;
use app\common\model\Member as MemberModel;
use app\common\model\ZhMemberAlllog as ZhMemberAlllogModel;
use app\common\model\ZhMemberLog as ZhMemberLogModel;
use app\common\model\MemberLoginIp as MemberLoginIpModel;
use think\Db;

/**
 * 首页展示控制器
 * Class Index
 * @package app\index\controller
 */
class Index extends Base
{
    /**
     * [getIndex2  后台首页数据]
     * type 1今日 2本周 3本月 4全年 5代表区间
     * @author [C。]
     * @return json
     */
    public function getIndex2()
    {
        $model = new MemberModel;
        $amodel = new ZhMemberAlllogModel;
        $lmodel = new ZhMemberLogModel;
        $lamodel = new LogAdminModel;
        $map = [];
        $map1 = [];
        $map2 = [];
        try{
            $data['all_members'] = $model->getAllCount(''); //总用户量
            $today_start_time = strtotime(date('Y-m-d'));
            $map['addtime'] = ['between',[$today_start_time,$today_start_time+24*60*60]];
            $data['today_members'] = $model->getAllCount($map); //今日新增用户量
            $data['alllog'] = $amodel->getAllCount(''); //总访问人次
            $data['log'] = $lmodel->getAllCount(''); //总访问人数
            $map1['create_time'] = ['between',[$today_start_time,$today_start_time+24*60*60]];
            $data['today_alllog'] = $amodel->getAllCount($map1); //今日访问人次
            $data['today_log'] = $lmodel->getAllCount($map1); //今日访问人数
            $yesterday_start_time = $today_start_time - 24*60*60;
            $map2['create_time'] = ['between',[$yesterday_start_time,$yesterday_start_time+24*60*60]];
            $data['yeaterday_log'] = $lmodel->getAllCount($map2); //昨日访问人数
            $data['state'] = $lamodel->getlist(['status'=>1],0,6,'admin_name,description,ip,create_time');
            foreach($data['state'] as &$v){
                $addtime = $v['create_time'];
                $v['addtime'] = get_last_time(strtotime($addtime));
                $v['img'] = config('home.no_user_headimg');
            }
        }catch (\Exception $e) {
            return admin_json(-1, $e->getMessage());
        }
        return admin_json(1, '获取成功',$data);
    }
    /**
     * [index  后台注册量和访问量趋势数据]
     * type 1今日 2本周 3本月 4全年 5代表区间
     * @author [C。]
     * @return json
     */
    public function getIndex1()
    {
        $param = input('param.');
        $time = [];
        try{
            if($param['type'] == 1){
                $i = 0;
                $todaytime = strtotime(date('Y-m-d'));
                for($i;$i<24;$i++){
                    $start = $todaytime+$i*60*60;
                    $end = $todaytime+60*60+$i*60*60;
                    if($param['ftype'] == 1){
                        $time[] = Db::name('member')->where("addtime >= $start AND addtime < $end")->count();
                    }else{
                        $time[] = Db::name('zh_member_alllog')->where("create_time >= $start AND create_time < $end")->count();
                    }
                }
            }elseif($param['type'] == 2){
                $i = 0;
                $da = date("w");
                if($da == 0){
                    $da = 7;
                }
                $todaytime = strtotime(date('Y-m-d'));
                $mondaytime = $todaytime - ($da-1)*24*60*60;
                for($i;$i<$da;$i++){
                    $start = $mondaytime + $i*24*60*60;
                    $end = $mondaytime + $i*24*60*60 + 24*60*60;
                    if($param['ftype'] == 1){
                        $time[] = Db::name('member')->where("addtime >= $start AND addtime < $end")->count();
                    }else{
                        $time[] = Db::name('zh_member_alllog')->where("create_time >= $start AND create_time < $end")->count();
                    }
                }
            }elseif($param['type'] == 3){
                $i = 0;
                $todaytime = strtotime(date('Y-m-d'));
                $day = date("d");
                $one = $todaytime - ($day-1)*24*60*60;
                for($i;$i<$day;$i++){
                    $start = $one + $i*24*60*60;
                    $end = $one + $i*24*60*60 + 24*60*60;
                    if($param['ftype'] == 1){
                        $time[] = Db::name('member')->where("addtime >= $start AND addtime < $end")->count();
                    }else{
                        $time[] = Db::name('zh_member_alllog')->where("create_time >= $start AND create_time < $end")->count();
                    }
                }
            }elseif($param['type'] == 4){
                $i = 0;
                $year = date('Y');
                $mon = date('m');
                for($i;$i<$mon;$i++){
                    $month = $i + 1;
                    $days = date("t",strtotime("$year-$month"));
                    $start = strtotime("$year-$month-1");
                    $end = strtotime("$year-$month-$days") + 24*60*60;
                    if($param['ftype'] == 1){
                        $time[] = Db::name('member')->where("addtime >= $start AND addtime < $end")->count();
                    }else{
                        $time[] = Db::name('zh_member_alllog')->where("create_time >= $start AND create_time < $end")->count();
                    }
                }
            }elseif($param['type'] == 5){
                $start = strtotime($param['start']);
                $end = strtotime($param['end']);
                $start_year = date('Y',$start);
                $start_mon = date('m',$start);
                $start_day = date("d",$start);
                $end_year = date('Y',$end);
                $end_mon = date('m',$end);
                $end_day = date("d",$end);
                $i = 0;
                if ($end - $start <= 30*24*60*60){
                    if($start_year == $end_year){
                        if($start_mon == $end_mon){
                            $day = $end_day - $start_day;
//                            for($i;$i<=$day;$i++){
//                                $start1 = $start + $i*24*60*60;
//                                $end1 = $start + $i*24*60*60 + 24*60*60;
//                                $time[date('Y年m月d日',$start1)] = Db::name('member')->where("addtime >= $start1 AND addtime < $end1")->count();
//                            }
                        }elseif ($end_mon - $start_mon >= 1){
                            $start_days = date("t",strtotime("$start_year-$start_mon"));
                            $month = $start_mon + 1;
                            $days = 0;
                            if($end_mon - $start_mon == 2){
                                $days = date("t",strtotime("$start_year-$month"));
                            }
                            $day = $start_days-$start_day+$end_day+$days;
                        }

                    }else{
                        $days = date("t",strtotime("$start_year-$start_mon"));
                        $day = $days-$start_day+$end_day;
//                        for($i;$i<=$day;$i++){
//                            $start1 = $start + $i*24*60*60;
//                            $end1 = $start + $i*24*60*60 + 24*60*60;
//                            $time[date('Y年m月d日',$start1)] = Db::name('member')->where("addtime >= $start1 AND addtime < $end1")->count();
//                        }
                    }
                    for($i;$i<=$day;$i++){
                        $start1 = $start + $i*24*60*60;
                        $end1 = $start + $i*24*60*60 + 24*60*60;
                        if($param['ftype'] == 1){
                            $time[date('Y-m-d',$start1)] = Db::name('member')->where("addtime >= $start1 AND addtime < $end1")->count();
                        }else{
                            $time[date('Y-m-d',$start1)] = Db::name('zh_member_alllog')->where("create_time >= $start1 AND create_time < $end1")->count();
                        }
                    }
                }elseif($end - $start > 30*24*60*60){
                    if($start_year == $end_year){
                        $mon = $end_mon - $start_mon;
                        for($i;$i<=$mon;$i++){
                            $start_mon1 = $start_mon + $i;
                            $start_mon2 = $start_mon1 + 1;
                            $start1 = strtotime("$start_year-$start_mon1-1");
                            $end1 = strtotime("$start_year-$start_mon2-1");
                            if($param['ftype'] == 1){
                                $time[$start_year.'年'.$start_mon1.'月'] = Db::name('member')->where("addtime >= $start1 AND addtime < $end1")->count();
                            }else{
                                $time[$start_year.'年'.$start_mon1.'月'] = Db::name('zh_member_alllog')->where("create_time >= $start1 AND create_time < $end1")->count();
                            }

                        }
                    }elseif($end_year - $start_year >= 1){
                        $mon = 12-$start_mon+$end_mon+12*($end_year - $start_year - 1);
                        for($i;$i<=$mon;$i++){
                            $start_mon = $start + 31*24*60*60*$i;
                            $end_mon = $start + 31*24*60*60*($i+1);
                            $new_year1 = date('Y',$start_mon);
                            $new_year2 = date('Y',$end_mon);
                            $start_mon1 = date('m',$start_mon);
                            $start_mon2 = date('m',$end_mon);
                            $start1 = strtotime("$new_year1-$start_mon1-1");
                            $end1 = strtotime("$new_year2-$start_mon2-1");
                            if($param['ftype'] == 1){
                                $time[$new_year1.'年'.$start_mon1.'月'] = Db::name('member')->where("addtime >= $start1 AND addtime < $end1")->count();
                            }else{
                                $time[$new_year1.'年'.$start_mon1.'月'] = Db::name('zh_member_alllog')->where("create_time >= $start1 AND create_time < $end1")->count();
                            }
                        }
                    }
                }
            }
        }catch(\Exception $e){
            return admin_json(-1, '获取失败'.$e->getMessage());
        }
        return admin_json(1, '获取成功',$time);
    }
    /**
     * [index  后台首页数据]
     * @author [C。]
     * @return json
     */
    public function getIndex()
    {
        $param = input('param.');
        if(empty($param['d'])){
            $howmany = 6;
        }else{
            $howmany = $param['d'];
        }

        $model = new MemberModel;
        $almodel = new ZhMemberAlllogModel;
        $lmodel = new ZhMemberLogModel;

        $user = $this->user;
        $num = 1 - $howmany ;
        $this->howmany = $howmany;

        $days = array();

        $mon1 = array();
        $mon2 = array();
        $psersonnum = array();
        $alllog = array();

        $tmon1 = 0;
        $tmon2 = 0;

        for ($i = $num; $i < 1; $i++) {
            $ndaystime0 = $this::unixtime('day', $i);
            $ndaystime59 = $ndaystime0 + 3600 * 24 - 1; //最后一秒

            $days[] = date('Y-m-d', $ndaystime59);

            $cond = ['addtime' => ['between', $ndaystime0 . ',' . $ndaystime59]]; //, 'states' => 1
            $mon1a = Db::name('member')->where($cond)->count();
            $alllog1 =  Db::name('zh_member_alllog')->where(['create_time' => ['between', $ndaystime0 . ',' . $ndaystime59]])->count();

            $cond = ['states' => 1, 'paytime' => ['between', $ndaystime0 . ',' . $ndaystime59]];
            $mon2a = Db::name('recharge')->where($cond)->sum('amt');

            $personnuma = Db::name('recharge')->distinct(true)->field('memid')->where($cond)->count();
            $alllog[] = $alllog1;
            $mon1[] = $mon1a;
            $mon2[] = $mon2a;
            $psersonnum [] = $personnuma;
            $tmon1 += $mon1a;

            $tmon2 += $mon2a;


        }
        $data = array();

        //时间轴
        $data['days'] = $days;
        //访问量
        $data['all_logs'] = $alllog;
        //注册会员数
        $data['mon1'] = $mon1;
        //充值金额
        $data['mon2'] = $mon2;
        //募捐人数
        $data['psersonnum'] = $psersonnum;
        //当前时间段注册人数
        $data['tmon1'] = $tmon1;
        //当前时间段捐款总额
        $data['tmon2'] = number_format($tmon2,2);
        //总用户数
        $data['zmon1'] = Db::name('member')->count();
        //总募捐数
        $data['zmon2'] = Db::name('recharge')->where('states',1)->sum('amt');

        //当前时间
        $today = strtotime(date('Y-m-d'));

        //今日注册人数
        $map = [];
        $map1 = [];
        $map2 = [];
        $map['addtime'] = ['between',[$today,$today+24*60*60]];
        $data['today_user'] = $model->getAllCount($map);

        $map1['create_time'] = ['between',[$today,$today+24*60*60]];
        $data['all_log'] = $almodel->getAllCount('');
        $data['today_all_log'] = $almodel->getAllCount($map1);
        $data['log'] = $lmodel->getAllCount('');
        $data['today_log'] = $lmodel->getAllCount($map1);
        $map2['create_time'] = ['between',[$today-24*60*60,$today]];
        $data['yesterday_log'] = $lmodel->getAllCount($map2);
        //七天前的时间
        $sday = strtotime(date('Y-m-d')) - 3600*24*7;
        $ssday = $sday + 3600*24;
        //获取之前第七天注册人数
        $con = ['addtime' => ['between', $sday . ',' . $ssday]];
        $mem = Db::name('member')->where($con)->field('id')->select();
        $mem = array_column($mem,'id');
        $zmem = count($mem);

        if($zmem){
            //次日留存率
            $time1 = $today - 3600*24*6;
            $num1 = Db::name('login_record')->where('logintime',$time1)->where('memid','in',$mem)->count();
            $data['rate1'] = number_format(($num1 / $zmem) * 100,0);
            //第三日留存率
            $time2 = $today - 3600*24*5;
            $num2 = Db::name('login_record')->where('logintime',$time2)->where('memid','in',$mem)->count();
            $data['rate2'] = number_format(($num2 / $zmem) * 100,0);
            //第四日留存率
            $time3 = $today - 3600*24*4;
            $num3 = Db::name('login_record')->where('logintime',$time3)->where('memid','in',$mem)->count();
            $data['rate3'] = number_format(($num3 / $zmem) * 100,0);
            //第五日留存率
            $time4 = $today - 3600*24*3;
            $num4 = Db::name('login_record')->where('logintime',$time4)->where('memid','in',$mem)->count();
            $data['rate4'] = number_format(($num4 / $zmem) * 100,0);
            //第六日留存率
            $time5 = $today - 3600*24*2;
            $num5 = Db::name('login_record')->where('logintime',$time5)->where('memid','in',$mem)->count();
            $data['rate5'] = number_format(($num5 / $zmem) * 100,0);
            //第七日留存率
            $time6 = $today - 3600*24;
            $num6 = Db::name('login_record')->where('logintime',$time6)->where('memid','in',$mem)->count();
            $data['rate6'] = number_format(($num6 / $zmem) * 100,0);
        }else{
            $data['rate1'] = 0;
            $data['rate2'] = 0;
            $data['rate3'] = 0;
            $data['rate4'] = 0;
            $data['rate5'] = 0;
            $data['rate6'] = 0;
        }

        writelog('查看首页',1,$user);
        return json_encode($data);
    }


    /**
     * 获取一个基于时间偏移的Unix时间戳
     *
     * @param string $type 时间类型，默认为day，可选minute,hour,day,week,month,quarter,year
     * @param int $offset 时间偏移量 默认为0，正数表示当前type之后，负数表示当前type之前
     * @param string $position 时间的开始或结束，默认为begin，可选前(begin,start,first,front)，end
     * @param int $year 基准年，默认为null，即以当前年为基准
     * @param int $month 基准月，默认为null，即以当前月为基准
     * @param int $day 基准天，默认为null，即以当前天为基准
     * @param int $hour 基准小时，默认为null，即以当前年小时基准
     * @param int $minute 基准分钟，默认为null，即以当前分钟为基准
     * @return int 处理后的Unix时间戳
     */
    public static function unixtime($type = 'day', $offset = 0, $position = 'begin', $year = null, $month = null, $day = null, $hour = null, $minute = null) {
        $year = is_null($year) ? date('Y') : $year;
        $month = is_null($month) ? date('m') : $month;
        $day = is_null($day) ? date('d') : $day;
        $hour = is_null($hour) ? date('H') : $hour;
        $minute = is_null($minute) ? date('i') : $minute;
        $position = in_array($position, array('begin', 'start', 'first', 'front'));
        switch ($type) {
            case 'minute':
                $time = $position ? mktime($hour, $minute + $offset, 0, $month, $day, $year) : mktime($hour, $minute + $offset, 59, $month, $day, $year);
                break;
            case 'hour':
                $time = $position ? mktime($hour + $offset, 0, 0, $month, $day, $year) : mktime($hour + $offset, 59, 59, $month, $day, $year);
                break;
            case 'day':
                $time = $position ? mktime(0, 0, 0, $month, $day + $offset, $year) : mktime(23, 59, 59, $month, $day + $offset, $year);
                break;
            case 'week':
                $time = $position ?
                    mktime(0, 0, 0, $month, $day - date("w", mktime(0, 0, 0, $month, $day, $year)) + 1 - 7 * (-$offset), $year) :
                    mktime(23, 59, 59, $month, $day - date("w", mktime(0, 0, 0, $month, $day, $year)) + 7 - 7 * (-$offset), $year);
                break;
            case 'month':
                $time = $position ? mktime(0, 0, 0, $month + $offset, 1, $year) : mktime(23, 59, 59, $month + $offset, get_month_days($month + $offset, $year), $year);
                break;
            case 'quarter':
                $time = $position ?
                    mktime(0, 0, 0, 1 + ((ceil(date('n', mktime(0, 0, 0, $month, $day, $year)) / 3) + $offset) - 1) * 3, 1, $year) :
                    mktime(23, 59, 59, (ceil(date('n', mktime(0, 0, 0, $month, $day, $year)) / 3) + $offset) * 3, get_month_days((ceil(date('n', mktime(0, 0, 0, $month, $day, $year)) / 3) + $offset) * 3, $year), $year);
                break;
            case 'year':
                $time = $position ? mktime(0, 0, 0, 1, 1, $year + $offset) : mktime(23, 59, 59, 12, 31, $year + $offset);
                break;
            default:
                $time = mktime($hour, $minute, 0, $month, $day, $year);
                break;
        }
        return $time;
    }
    /**
     * [getHotnews  获取热门资讯]
     * @author [C。]
     * @return json
     */
    public function getHotnews()
    {
        $param = input('param.');
        $model = new NewsModel();
        $map = [];
        if(!empty($param['start']) && !empty($param['end'])){
            $map['addtime'] = ['between',[strtotime($param['start']),strtotime($param['end'])]];
        }
        try{
            $map['states'] = ['neq',-1];
            $list = $model->getHotlist($map,0,20,'id,title,cover,read_num');
            foreach($list as &$v){
                $http = substr($v['cover'],0,4);
                if($http != 'http') {
                    $v['cover'] = config('domain_name') .$v['cover'];
                }
            }
        }catch(\Exception $e){
            return admin_json(-1, '获取失败'.$e->getMessage());
        }
        return admin_json(1, '获取成功',$list);
    }
    /**
     * [getHotCompany  获取热门寺院前5]
     * @author [C。]
     * @return json
     */
    public function getHotCompany()
    {
        $param = input('param.');
        $model = new CompanyModel();
        $map = '';
        if(!empty($param['start']) && !empty($param['end'])){
            $map = 'where addtime between '.strtotime($param['start']).' and '.strtotime($param['end']);
        }
        try{
            $sql = 'SELECT itemid, count( * ) AS count  FROM app_ilike '.$map.' GROUP BY itemid  ORDER BY count DESC LIMIT 7';
            $list = Db::query($sql);
            foreach($list as &$v){
                $company = $model->findData($v['itemid'],'id','comname,compic,province,city,qu');
                $http = substr($company['compic'],0,4);
                if($http != 'http') {
                    $v['compic'] = config('domain_name') . $company['compic'];
                }else{
                    $v['compic'] = $company['compic'];
                }
                $v['comname'] = $company['comname'];
                $v['province'] = $company['province'];
                $v['city'] = $company['city'];
                $v['qu'] = $company['qu'];
            }
        }catch(\Exception $e){
            return admin_json(-1, '获取失败'.$e->getMessage());
        }
        return admin_json(1, '获取成功',$list);
    }
    /**
     * [getHotTopic  获取热门论坛前10]
     * @author [C。]
     * @return json
     */
    public function getHotTopic()
    {
        $model = new MemberModel();
        try{
            $sql = 'SELECT memid id, count(*) AS count  FROM app_topic GROUP BY memid  ORDER BY count DESC LIMIT 10';
            $list = Db::query($sql);
            foreach($list as &$v){
                $mem = $model->findData($v['id'],'id','tel,username,img');
                $http = substr($mem['img'],0,4);
                if($http != 'http') {
                    $v['img'] = config('domain_name') . $mem['img'];
                }else{
                    $v['img'] = $mem['img'];
                }
                $v['tel'] = $mem['tel'];
                $v['username'] = $mem['username'];
            }
        }catch(\Exception $e){
            return admin_json(-1, '获取失败'.$e->getMessage());
        }
        return admin_json(1, '获取成功',$list);
    }
    /**
     * [getRegist  寺院注册人数排行]
     * @author [C。]
     * @return json
     */
    public function getRegist()
    {
        $param = input('param.');
        $model = new CompanyModel();
        $map = '';
        if (!empty($param['start']) && !empty($param['end'])) {
            $map = 'where addtime between ' . strtotime($param['start']) . ' and ' . strtotime($param['end']);
        }
        try {
            $sql = 'SELECT register_comid, count( * ) AS count  FROM app_member ' . $map . ' GROUP BY register_comid  ORDER BY count DESC LIMIT 7';
            $list = Db::query($sql);
            foreach($list as &$v){
                if(!empty($v['register_comid'])){
                    $company = $model->findData($v['register_comid'],'id','comname');
                    $v['comname'] = $company['comname'];
                }else{
                    $v['comname'] = 'APP';
                }
            }
        }catch(\Exception $e){
            return admin_json(-1, '获取失败'.$e->getMessage());
        }
        return admin_json(1, '获取成功',$list);
    }
    /**
     * [getGlance  寺院访问排行]
     * @author [C。]
     * @return json
     */
    public function getGlance()
    {
        $param = input('param.');
        $map = [];
        $this->getPageAndSize($param);
        $model = new CompanyModel;
        try {
            if(!empty($param['alllog'])){
                $order = ['alllog'=>$param['alllog']];
            }elseif(!empty($param['log'])){
                $order = ['log'=>$param['log']];
            }

            $count = $model->getCount1($map);//满足条件的总数
            $allpage = intval(ceil($count / $this->size));//总页数
            $lists = $model->getList1($map, $this->from, $this->size,'comname,alllog,log',$order);
        }catch (\Exception $e) {
            return admin_json(-1,$e->getMessage());
        }
        return admin_json(1, '获取成功',[
            'count' => $count,//总记录数
            'allpage' => $allpage,  //总页数
            'lists' => $lists,  //列表数据
        ]);
    }
    /**
     * [getComareanum  寺院区域数量排行]
     * @author [C。]
     * @return json
     */
    public function getComareanum()
    {
        $model = new ZhMemberAlllogModel;
        try {
            $company = Db::query('select province as name,count(province) as value from app_company where province <> "" and states <> -1 group by province order by value desc');
            foreach($company as &$v){
                $province = $v['name'];
                $v['pv'] = $model->getAllCount(['province'=>$v['name']]);
                $lognum = Db::query("select count(distinct mid) as num from app_zh_member_log where province = '{$province}'");
                $v['uv'] = $lognum[0]['num'];
                $alllognum = Db::query("select count(distinct ip) as num from app_zh_member_alllog where province = '{$province}'");
                $v['ip'] = $alllognum[0]['num'];
                $v['name'] = str_replace(array('省','特别行政区','自治区','市'), '', $v['name']);
            }
        }catch (\Exception $e) {
            return admin_json(-1,$e->getMessage());
        }
        return admin_json(1,'获取成功',$company);
    }
    /**
     * [getMemareanum  用户区域数量排行]
     * @author [C。]
     * @return json
     */
    public function getMemareanum()
    {
        $model = new MemberLoginIpModel;
        try {
            $member = Db::query('select province as name,count(province) as value from app_member_login_ip group by province order by value desc');
            foreach($member as &$v){
                $province = $v['name'];
                $v['uv'] = $model->getAllCount(['province'=>$v['name']]);
                $ipnum = Db::query("select count(distinct ip) as num from app_member_login_ip where province = '{$province}'");
                $v['ip'] = $ipnum[0]['num'];
                $v['name'] = str_replace(array('省','特别行政区','自治区','市'), '', $v['name']);
            }
        }catch(\Exception $e){
            return admin_json(-1,$e->getMessage());
        }
        return admin_json(1,'获取成功',$member);
    }
}
